<template>
	<view>
		<uni-file-picker :limit="limit" class="imgView" file-mediatype="image" v-model="activeValue" @select="select"
			@progress="progress" @success="success" @fail="fail">
			<text>+</text>
			<text>添加封面</text>
		</uni-file-picker>
	</view>
</template>

<script>
	import { getAccessToken,getRefreshToken } from '@/utils/auth'
	import config from '@/config'
	export default {
		name: "imageUpload",
		props: {
		    imgvalue: {
					type:Array,
					default:[]
				},
		    // 图片数量限制
		    limit: {
		      type: Number,
		      default: 5,
		    },
		    // 大小限制(MB)
		    fileSize: {
		      type: Number,
		      default: 5,
		    },
		    // 文件类型, 例如['png', 'jpg', 'jpeg']
		    fileType: {
		      type: Array,
		      default: () => ["png", "jpg", "jpeg"],
		    },
		  },
		data() {
			return {
				activeValue:this.imgvalue,
				filePathsList:[],
				headers: { 
					'Authorization': "Bearer " + getAccessToken(),
					'tenant-id': 1,
				}, // 设置上传的请求头部
			};
		},
		methods: {
			// 获取上传状态
			async select(res) {
				console.log('选择文件：', res)
				await this.uploadImg(res.tempFilePaths);
			},
			async uploadImg(tempFilePaths) {
				if (!tempFilePaths.length) return;
				const path = tempFilePaths.pop();
				this.filePathsList.push({
					url: path,
					name: ""
				})
				const [err, {
					data
				}] = await uni.uploadFile({
					url: config.baseUrl + "/admin-api/infra/file/upload", // 请求地址
					filePath: path,
					name: 'file',
					header: this.headers,
				});
				if (data == null || data == '') {
					// upload fail
					
					this.filePathsList.pop()
					uni.showToast({
						title: "上传失败",
						icon: "none"
					})
				} else {
					uni.showToast({
						title: "图片上传成功",
						icon: "none"
					})
					this.filePathsList[this.filePathsList.length - 1].name = data
					let _data = JSON.parse(data);
					this.activeValue=[]
					this.activeValue.push({ name: _data.data, url: _data.data })
				}
				//this.uploadImg(tempFilePaths);
			},
			getImgValue(){
				return this.activeValue
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			}
		}
	}
</script>

<style>

</style>
